<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * 商品分类关联模型
 * 
 * @property int $id 主键ID
 * @property int $goods_id 商品ID
 * @property int $category_id 分类ID
 * @property string $category_ids 分类IDs
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 * @property int $goods_option_id 分类组关联商品规格ID
 */
class GoodsCategory extends Model
{
    protected $table = 'ims_yz_goods_category';
    
    protected $guarded = [];
    
    // 禁用自动时间戳管理
    public $timestamps = false;
    
    protected $casts = [
        'created_at' => 'integer',
        'updated_at' => 'integer',
        'deleted_at' => 'integer',
        'goods_id' => 'integer',
        'category_id' => 'integer',
        'goods_option_id' => 'integer'
    ];
    
    /**
     * 关联商品
     */
    public function goods()
    {
        return $this->belongsTo(Goods::class, 'goods_id', 'id');
    }
    
    /**
     * 关联分类
     */
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }
    
    /**
     * 按商品ID筛选
     */
    public function scopeByGoodsId($query, $goodsId)
    {
        return $query->where('goods_id', $goodsId);
    }
    
    /**
     * 按分类ID筛选
     */
    public function scopeByCategoryId($query, $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }
    
    /**
     * 重写保存方法，手动处理时间戳
     */
    public function save(array $options = [])
    {
        if (!$this->exists) {
            $this->created_at = time();
        }
        $this->updated_at = time();
        
        return parent::save($options);
    }
    
    /**
     * 重写删除方法，手动处理软删除
     */
    public function delete()
    {
        $this->deleted_at = time();
        return $this->save();
    }
}